<?php

require_once ('Joob/Controller/Abstract.php');

class Joob_Controller_Task extends Joob_Controller_Abstract {
	
	protected $_classMethods;
	
	//input filters
	protected $_filters;
	
	//cached parameters
	protected $_cachedParams;
	
	public function __construct()	{
		$this->_filters = array();
		$this->_cachedParams = array();
	}
	
	public function addFilter($filter)	{
		$this->_filters[] = $filter;
	}
	
	/**
	 * Retrieve the request parameter and filter it using additional filters if any
	 * @param $key the request parameter's name
	 * @param $default the default value
	 * @param $filters additional filters to purify the parameters, default is empty
	 * @param overrideFilter should we omit the previous filter?
	 */
	public function getParam($key, $default = null, $filters = array(), $overrideFilter = false)	{
		$value = $this->getRequest()->getParam($key);
		if ($value == null)	{
			//Do not cache since the default value can be changed over time
			return $default;
		}
		
		//FIXME: Should we revalidate the cache if the filters are changed
		if (isset($this->_cachedParams[$key]))	{
			return $this->_cachedParams[$key];
		}
		
		if ($overrideFilter == false)	{
			$filters = array_merge($filters, $this->_filters);
		}
		
		foreach($filters as $filter)	{
			$value = $filter->filter($value);
		}
		
		//cache it
		$this->_cachedParams[$key] = $value;
		return $value;
	}
	
	public function dispatch($task) {
		$this->preDispatch ();
		
		if (null === $this->_classMethods) {
			$this->_classMethods = get_class_methods ( $this );
		}
		
		if (in_array ( $task, $this->_classMethods )) {
			$this->$task ();
		} else {
			$this->__call ( $task, array () );
		}
		$this->postDispatch ();
	}
	
	public function __call($methodName, $params) {
		if ('Task' == substr ( $methodName, - 4 )) {
			$task = substr($methodName, 0, strlen($methodName) - 4);
			require_once 'Joob/Exceptions/NotFound.php';
			throw new Joob_Exceptions_NotFound (sprintf('Task "%s" does not exist', $task));
		} else {
			throw new Exception(sprintf('Method "%s" does not exist', $methodName), 500);
		}
	}
}

?>